import React, { useState } from "react";
import { Select, Input, Button, Tag, Dropdown } from "antd";
import {
  SearchOutlined,
  FilterOutlined,
  SortAscendingOutlined,
  MoreOutlined,
  EditOutlined,
  DeleteOutlined
} from "@ant-design/icons";
import { DragDropContext } from "@hello-pangea/dnd";
import type { DropResult } from "@hello-pangea/dnd";
import type { MenuProps } from "antd";
import { useAppDispatch } from "../../../hooks/redux";
import { moveTaskLocal, moveTask } from "../../../store/projectSlice";
import { TaskStatus, TaskPriority } from "../../../types/project";
import type { Project } from "../../../types/project";
import TaskGroup from "./TaskGroup";
import EditProjectModal from "./EditProjectModal";

const { Option } = Select;

interface ProjectBoardProps {
  project: Project;
}

const ProjectBoard: React.FC<ProjectBoardProps> = ({ project }) => {
  const dispatch = useAppDispatch();
  const [isDragDisabled, setIsDragDisabled] = useState(false);

  // 任务筛选状态
  const [taskFilters, setTaskFilters] = useState({
    search: "",
    status: [] as string[],
    priority: [] as string[],
    milestone: [] as string[],
    startDate: undefined as [string, string] | undefined,
    dueDate: undefined as [string, string] | undefined
  });

  const [taskSort, setTaskSort] = useState({
    field: "manual" as string,
    order: "desc" as "asc" | "desc"
  });

  // 项目编辑状态
  const [editProjectVisible, setEditProjectVisible] = useState(false);

  // 筛选和排序选项
  const statusOptions = [
    { value: TaskStatus.NOT_STARTED, label: "未开始", color: "#d9d9d9" },
    { value: TaskStatus.IN_PROGRESS, label: "进行中", color: "#1890ff" },
    { value: TaskStatus.COMPLETED, label: "已完成", color: "#52c41a" }
  ];

  const priorityOptions = [
    { value: TaskPriority.LOW, label: "低优先级", color: "#87d068" },
    { value: TaskPriority.MEDIUM, label: "中优先级", color: "#108ee9" },
    { value: TaskPriority.HIGH, label: "高优先级", color: "#f50" },
    { value: TaskPriority.URGENT, label: "紧急", color: "#ff4d4f" }
  ];

  const milestoneOptions = [
    "M0 - 项目启动",
    "M1 - 需求确认",
    "M1 - 技术选型",
    "M2 - 环境搭建",
    "M2 - 设计完成",
    "M3 - 核心功能"
  ];

  const sortOptions = [
    { value: "manual", label: "手动排序" },
    { value: "title", label: "标题" },
    { value: "status", label: "状态" },
    { value: "priority", label: "优先级" },
    { value: "dueDate", label: "截止时间" },
    { value: "createdAt", label: "创建时间" },
    { value: "updatedAt", label: "更新时间" }
  ];

  // 筛选和排序处理函数
  const handleTaskFilterChange = (key: string, value: any) => {
    setTaskFilters(prev => ({ ...prev, [key]: value }));
  };

  const handleTaskSortChange = (field: string) => {
    const newOrder = taskSort.field === field && taskSort.order === "desc" ? "asc" : "desc";
    setTaskSort({ field, order: newOrder });
  };

  const clearTaskFilters = () => {
    setTaskFilters({
      search: "",
      status: [],
      priority: [],
      milestone: [],
      startDate: undefined,
      dueDate: undefined
    });
  };

  const getActiveFiltersCount = () => {
    return Object.values(taskFilters).filter(
      value => value !== undefined && value !== null && (Array.isArray(value) ? value.length > 0 : value !== "")
    ).length;
  };

  // 拖拽处理
  const handleDragEnd = async (result: DropResult) => {
    const { destination, source, draggableId } = result;

    if (!destination || !project || isDragDisabled) {
      console.log("拖拽取消：没有目标位置或项目为空或拖拽被禁用");
      return;
    }

    if (destination.droppableId === source.droppableId && destination.index === source.index) {
      console.log("拖拽取消：位置没有变化");
      return;
    }

    console.log("拖拽操作:", {
      taskId: draggableId,
      from: { groupId: source.droppableId, index: source.index },
      to: { groupId: destination.droppableId, index: destination.index }
    });

    // 禁用拖拽以防止并发操作
    setIsDragDisabled(true);

    try {
      // Optimistic update
      dispatch(
        moveTaskLocal({
          taskId: draggableId,
          sourceGroupId: source.droppableId,
          targetGroupId: destination.droppableId,
          targetIndex: destination.index
        })
      );

      // Server update
      await dispatch(
        moveTask({
          projectId: project.id,
          taskId: draggableId,
          sourceGroupId: source.droppableId,
          targetGroupId: destination.droppableId,
          targetIndex: destination.index
        })
      ).unwrap();

      console.log("任务移动成功");
    } catch (error) {
      console.error("任务移动失败:", error);
      // TODO: 实现回滚逻辑
    } finally {
      // 重新启用拖拽
      setTimeout(() => {
        setIsDragDisabled(false);
      }, 100);
    }
  };

  // 项目操作菜单
  const projectMenuItems: MenuProps["items"] = [
    {
      key: "edit",
      label: "编辑项目",
      icon: <EditOutlined />,
      onClick: () => {
        setEditProjectVisible(true);
      }
    },
    {
      key: "delete",
      label: "删除项目",
      icon: <DeleteOutlined />,
      danger: true,
      onClick: () => {
        // TODO: 实现删除项目功能
        console.log("删除项目:", project.id);
      }
    }
  ];

  return (
    <div className="bg-white rounded-lg shadow-sm border border-gray-200 p-6 mb-6">
      {/* 项目头部信息和操作 */}
      <div className="flex items-start justify-between mb-6">
        <div className="flex-1">
          <h2 className="text-xl font-semibold text-gray-900 mb-2">{project.title}</h2>
          {project.description && <p className="text-gray-600">{project.description}</p>}
        </div>
        <Dropdown menu={{ items: projectMenuItems }} trigger={["click"]}>
          <Button icon={<MoreOutlined />} type="text" />
        </Dropdown>
      </div>

      {/* 内嵌的任务筛选器 */}
      <div className="bg-gray-50 rounded-lg p-4 mb-6">
        <div className="flex flex-wrap items-center gap-4 mb-4">
          <div className="flex items-center gap-2">
            <SearchOutlined className="text-gray-400" />
            <Input
              placeholder="搜索任务标题..."
              value={taskFilters.search}
              onChange={e => handleTaskFilterChange("search", e.target.value)}
              className="w-64"
              allowClear
            />
          </div>

          <Select
            mode="multiple"
            placeholder="状态筛选"
            value={taskFilters.status}
            onChange={value => handleTaskFilterChange("status", value)}
            className="min-w-32"
            allowClear
          >
            {statusOptions.map(option => (
              <Option key={option.value} value={option.value}>
                <Tag color={option.color} className="mr-1">
                  {option.label}
                </Tag>
              </Option>
            ))}
          </Select>

          <Select
            mode="multiple"
            placeholder="优先级筛选"
            value={taskFilters.priority}
            onChange={value => handleTaskFilterChange("priority", value)}
            className="min-w-32"
            allowClear
          >
            {priorityOptions.map(option => (
              <Option key={option.value} value={option.value}>
                <Tag color={option.color} className="mr-1">
                  {option.label}
                </Tag>
              </Option>
            ))}
          </Select>

          <Select
            mode="multiple"
            placeholder="里程碑筛选"
            value={taskFilters.milestone}
            onChange={value => handleTaskFilterChange("milestone", value)}
            className="min-w-40"
            allowClear
          >
            {milestoneOptions.map(milestone => (
              <Option key={milestone} value={milestone}>
                {milestone}
              </Option>
            ))}
          </Select>
        </div>

        <div className="flex items-center justify-between">
          <div className="flex items-center gap-4">
            <div className="flex items-center gap-2">
              <SortAscendingOutlined className="text-gray-400" />
              <span className="text-sm text-gray-600">排序:</span>
              <Select value={taskSort.field} onChange={handleTaskSortChange} className="w-32">
                {sortOptions.map(option => (
                  <Option key={option.value} value={option.value}>
                    {option.label}
                  </Option>
                ))}
              </Select>
              <Button
                size="small"
                type={taskSort.order === "desc" ? "primary" : "default"}
                onClick={() => setTaskSort({ ...taskSort, order: taskSort.order === "desc" ? "asc" : "desc" })}
              >
                {taskSort.order === "desc" ? "降序" : "升序"}
              </Button>
            </div>
          </div>

          <div className="flex items-center gap-2">
            {getActiveFiltersCount() > 0 && (
              <Tag color="blue" className="mr-2">
                <FilterOutlined className="mr-1" />
                {getActiveFiltersCount()} 个筛选条件
              </Tag>
            )}
            <Button onClick={clearTaskFilters} size="small">
              清空筛选
            </Button>
          </div>
        </div>
      </div>

      {/* 任务看板 */}
      <DragDropContext onDragEnd={handleDragEnd}>
        <div className="flex gap-6 overflow-x-auto pb-4">
          {[...project.groups]
            .sort((a, b) => a.order - b.order)
            .map(group => (
              <TaskGroup
                key={group.id}
                group={group}
                projectId={project.id}
                taskFilters={taskFilters}
                taskSort={taskSort}
                isDragDisabled={isDragDisabled}
              />
            ))}
        </div>
      </DragDropContext>

      {/* 项目编辑弹窗 */}
      <EditProjectModal
        visible={editProjectVisible}
        project={project}
        onCancel={() => setEditProjectVisible(false)}
        onSuccess={() => setEditProjectVisible(false)}
      />
    </div>
  );
};

export default ProjectBoard;
